package com.terracloud.server.config;

import com.terracloud.server.service.stats.PhysicalMetricsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

/**
 * 指标收集配置类
 */
@Slf4j
@Configuration
@EnableScheduling
public class MetricsConfig implements SchedulingConfigurer {

    /**
     * 物理资源指标收集服务
     *
     * @param metricsProperties 指标配置属性
     * @return PhysicalMetricsService实例
     */
    @Bean
    public PhysicalMetricsService physicalMetricsService(MetricsProperties metricsProperties) {
        log.info("初始化物理资源指标收集服务，PushGateway地址: {}", metricsProperties.getUrl());
        return new PhysicalMetricsService(metricsProperties);
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(Executors.newScheduledThreadPool(2));
    }

    /**
     * 注册物理资源指标收集的定时任务
     *
     * @param physicalMetricsService 物理指标服务
     * @param metricsProperties 指标配置属性
     * @return ScheduledExecutorService实例
     */
    @Bean
    public ScheduledExecutorService scheduledMetricsCollector(
            PhysicalMetricsService physicalMetricsService,
            MetricsProperties metricsProperties) {
        
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
        
        // 只有当pushIntervalMs大于0时才注册定时任务
        if (metricsProperties.getPushIntervalMs() > 0) {
            log.info("注册物理资源指标自动收集任务，间隔: {} ms", metricsProperties.getPushIntervalMs());
            scheduler.scheduleAtFixedRate(
                    physicalMetricsService::collectAndPushMetrics,
                    10000, // 初始延迟10秒
                    metricsProperties.getPushIntervalMs(),
                    java.util.concurrent.TimeUnit.MILLISECONDS);
        } else {
            log.info("物理资源指标自动收集任务已禁用 (pushIntervalMs = 0)");
        }
        
        return scheduler;
    }
}